package com.zyh.filter;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLogin implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String uri = httpServletRequest.getRequestURI();
        //判断当前请求地址是否登录地址
        if(uri.contains("Login") || uri.contains("login")){
            //登录请求，直接放行
            return true;
        }else{
            //判断用户是否登录
            if(httpServletRequest.getSession().getAttribute("user")!=null){
                //说明已经登录，放行
                return true;
            }else{
                //没有登录，跳转到登录界面
                httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/user/login_form.jsp");
            }
        }

        //默认拦截
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
